package sql

import (
	"fmt"
	"sort"

	"github.com/tealeg/xlsx"
)

func ExportToXlsx(excelFile string, datas []Dict) (err error) {
	file := xlsx.NewFile()
	// Create a new sheet.
	sheet, _ := file.AddSheet("Sheet1")
	keys := []string{}
	for k := range datas[0] {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool {
		if byte(keys[i][0]) != byte(keys[j][0]) {
			return byte(keys[i][0]) < byte(keys[j][0])
		} else {
			return len(keys[i]) < len(keys[j])
		}

	})
	row := sheet.AddRow()
	for _, k := range keys {
		cell := row.AddCell()
		cell.Value = k
	}

	for no, n := range keys {
		sheet.SetColWidth(no, no, float64(len(n))*1.5)
	}

	for _, v := range datas {
		row := sheet.AddRow()

		for _, kname := range keys {
			value := v[kname]
			cell := row.AddCell()
			cell.Value = fmt.Sprint(value)
		}

	}
	err = file.Save(excelFile)
	return
}
